package com.frame.sentinel.handler;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException;
import com.alibaba.csp.sentinel.slots.system.SystemBlockException;
import com.frame.common.core.util.ResponseUtils;
import com.frame.common.tools.result.ResultCode;
import com.frame.common.tools.result.ServiceResult;

import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * sentinel 异常处理
 *
 * @auther zhangwj
 * @date 2021/4/8 下午8:21
 */
@Component
public class SentinelExceptionHandler implements BlockExceptionHandler {

    @Override
    public void handle(HttpServletRequest httpServletRequest,
                       HttpServletResponse httpServletResponse, BlockException e) throws Exception {
        httpServletResponse.setStatus(HttpStatus.FORBIDDEN.value());
        String msg;
        if (e instanceof FlowException) {
            msg = "接口服务限流";
        } else if (e instanceof DegradeException) {
            msg = "接口服务降级";
        } else if (e instanceof ParamFlowException) {
            msg = "热点参数限流";
        } else if (e instanceof SystemBlockException) {
            msg = "系统规则限流";
        } else if (e instanceof AuthorityException) {
            msg = "授权规则不通过";
        } else {
            msg = "未知Sentinel异常";
        }
        ResponseUtils.writeJson(httpServletResponse, ServiceResult.getFailureResult(ResultCode.SENTINEL_ERROR.getCode(), msg));
    }
}
